package com.yuan.plugin.net;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.yuan.plugin.callback.NetworkCallBack;

public class RChungNet {

	public static final int CATEGORY1 = 300;
	public static final int CATEGORY2 = 301;
	public static final int CATEGORY3 = 302;

	public static final int GOODSLISTFGM = 400;
	public static final int ORDERSLISTFGM = 401;
	public static final int MSGLISTFGM = 402;
	public static final int MELISTFGM = 403;
	public static final int GOODSMULTOPTIONS = 404;
	public static final int GOODSDETAIL = 405;

	public static final int GOODSSCREENING = 406;
	public static final int ADD2SHOPPINGCAR = 407;
	public static final int CARTLISTFGM = 408;
	public static final int CARTDELETE = 409;
	public static final int CHECKCART = 410;

	public static final int SUBMITORDER = 411;

	public static final int ORDERLIST = 412;
	public static final int ORDERDETAIL = 413;

	public static final int ORDERGOODSLIST = 500;
	public static final int ORDERSTATUS = 501;
	public static final int ORDERSCREENING = 502;

	public static final int ORDERGOODSLIST_S = 503;
	public static final int LOGINSUBMMIT = 504; // 登录

	public static final int OUTSTORESEND = 505; // 出库发货
	public static final int RETURNGOODS = 506; // 退货
	public static final int RECEIVEADDRLIST = 507; // 收货地址列表
	public static final int ADDRESSSUBMIT = 508; // 编辑收货地址
	public static final int EDITPERSONINFO = 509; // 编辑用户个人信息
	
	public static final int RETURNSCONTENT = 510;//退单详情
	public static final int RETURNSGOODSLIST = 511;//退货清单
	public static final int RETURNSSENDMODE = 512;//退货配送方式
	
	public static final int REQUESTACCOUNT = 600;//请求账户信息
	public static final int SUBMITACCOUNT = 601;//提交帐号信息
	
	public static final int MOBILENET = 0;
	public static final int WIFI = 1;
	public static final int UNKNOW = 2;
	public static final int TIMEOUT = 10000;
	public static final int post = Request.Method.POST;
	public static final int get = Request.Method.GET;

	/**
	 * 以普通的post方式进行提交
	 * 
	 * @param context
	 * @param str_url
	 * @param type
	 * @param params
	 */
	public static void doPost(Fragment fragment, String str_url, final int type, final Map<String, String> params) {
		final NetworkCallBack callBack = (NetworkCallBack) fragment;
		RequestQueue requestQueue = VolleySingleton.getInstance(fragment.getContext()).getRequestQueue();
		StringRequest stringRequest = new StringRequest(Request.Method.POST, str_url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				Log.d("TAG", response);
				callBack.networkSuccess(type, response);
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("TAG", error.getMessage(), error);
				callBack.networkFailure(type, error);
			}
		}) {
			@Override
			protected Map<String, String> getParams() {
				// 在这里设置需要post的参数
				return params;
			}
		};
		stringRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		requestQueue.add(stringRequest);
	}

	/**
	 * 以普通的post方式进行提交
	 * 
	 * @param context
	 * @param str_url
	 * @param type
	 * @param params
	 */
	public static void doPost(Context context, String str_url, final int type, final Map<String, String> params) {
		final NetworkCallBack callBack = (NetworkCallBack) context;
		RequestQueue requestQueue = VolleySingleton.getInstance(context).getRequestQueue();
		Log.d("params", params.toString());
		StringRequest stringRequest = new StringRequest(Request.Method.POST, str_url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				Log.d("TAG", response);
				callBack.networkSuccess(type, response);
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("TAG", error.getMessage(), error);
				callBack.networkFailure(type, error);
			}
		}) {
			@Override
			protected Map<String, String> getParams() {
				// 在这里设置需要post的参数
				return params;
			}
		};
		stringRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		Log.e("TAG", stringRequest.toString());
		requestQueue.add(stringRequest);
	}

	public static void doPost(Context context, final NetworkCallBack callBack, String str_url, final int type,
			final Map<String, String> params) {
		RequestQueue requestQueue = VolleySingleton.getInstance(context).getRequestQueue();
		StringRequest stringRequest = new StringRequest(Request.Method.POST, str_url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				Log.d("TAG", response);
				callBack.networkSuccess(type, response);
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("TAG", error.getMessage(), error);
				callBack.networkFailure(type, error);
			}
		}) {
			@Override
			protected Map<String, String> getParams() {
				// 在这里设置需要post的参数
				return params;
			}
		};
		stringRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		requestQueue.add(stringRequest);
	}

	/**
	 * 以json串的post请求方式进行提交
	 * 
	 * @param context
	 * @param str_url
	 * @param type
	 * @param params
	 */
	public static void doJsonPost(Context context, String str_url, final int type, final Map<String, String> params) {
		final NetworkCallBack callBack = (NetworkCallBack) context;
		RequestQueue requestQueue = VolleySingleton.getInstance(context).getRequestQueue();
		JSONObject jsonObject = new JSONObject(params);
		JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Method.POST, str_url, jsonObject,
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						Log.d("TAG", response.toString());
						callBack.networkSuccess(type, response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e("TAG", error.getMessage(), error);
						callBack.networkFailure(type, error);
					}
				}) {
			// 注意此处override的getParams()方法,在此处设置post需要提交的参数根本不起作用
			// 必须象上面那样,构成JSONObject当做实参传入JsonObjectRequest对象里
			// 所以这个方法在此处是不需要的
			// @Override
			// protected Map<String, String> getParams() {
			// Map<String, String> map = new HashMap<String, String>();
			// map.put("name1", "value1");
			// map.put("name2", "value2");

			// return params;
			// }

			@Override
			public Map<String, String> getHeaders() {
				HashMap<String, String> headers = new HashMap<String, String>();
				headers.put("Accept", "application/json");
				headers.put("Content-Type", "application/json; charset=UTF-8");

				return headers;
			}
		};
		requestQueue.add(jsonRequest);
	}

	public static void doGet(Context context, String str_url, final int type) {
		final NetworkCallBack callBack = (NetworkCallBack) context;

		// 1 创建RequestQueue对象
		RequestQueue mRequestQueue = Volley.newRequestQueue(context);
		// 2 创建StringRequest对象
		StringRequest mStringRequest = new StringRequest(str_url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				Log.d("TAG", response.toString());
				callBack.networkSuccess(type, response);
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("TAG", error.getMessage(), error);
				callBack.networkFailure(type, error);
			}
		});
		// 3 将StringRequest添加到RequestQueue
		mRequestQueue.add(mStringRequest);
	}

	/**
	 * 取得ImageLoader
	 * 
	 * @param context
	 * @return
	 */
	public static ImageLoader getImgLoader(Context context) {
//		RequestQueue requestQueue = VolleySingleton.getInstance(context).getRequestQueue();
		// ImageLoader mImageLoader = new ImageLoader(requestQueue, new
		// BitmapCache());
		ImageLoader mImageLoader = VolleySingleton.getInstance(context).getImageLoader();

		return mImageLoader;
	}

	/**
	 * 请求图片
	 * 
	 * @param context
	 * @param url
	 * @param imageView
	 * @param defaultImgID
	 * @param failureImgID
	 */
	public static Bitmap imageRequest(Context context, String url, ImageView imageView, int defaultImgID,
			int failureImgID) {
		// RequestQueue requestQueue =
		// VolleySingleton.getInstance(context).getRequestQueue();
		ImageListener listener = ImageLoader.getImageListener(imageView, defaultImgID, failureImgID);
		ImageLoader mImageLoader = VolleySingleton.getInstance(context).getImageLoader();
		ImageContainer container = mImageLoader.get(url, listener);
		return container.getBitmap();
	}

	/*
	 * public static void showImage(String url, ImageView imageView, int
	 * defaultID){ com.nostra13.universalimageloader.core.ImageLoader
	 * imageLoader =
	 * com.nostra13.universalimageloader.core.ImageLoader.getInstance();
	 * DisplayImageOptions options = new DisplayImageOptions.Builder()
	 * .showImageOnLoading(defaultID) // 设置图片下载期间显示的图片
	 * .showImageForEmptyUri(defaultID) // 设置图片Uri为空或是错误的时候显示的图片
	 * .showImageOnFail(defaultID) // 设置图片加载或解码过程中发生错误显示的图片 .cacheInMemory(true)
	 * // 设置下载的图片是否缓存在内存中 .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
	 * //.displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片 .build(); // 构建完成
	 * imageLoader.displayImage(url, imageView, options); }
	 */

	/**
	 * 使用此方法能够解决图片错乱问题
	 * 
	 * @param view
	 * @param defaultImageResId
	 * @param errorImageResId
	 * @param url
	 * @return
	 */
	public static ImageListener getImageListener(final ImageView view, final int defaultImageResId,
			final int errorImageResId, final String url) {
		return new ImageListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				if (errorImageResId != 0) {
					view.setImageResource(errorImageResId);
				}
			}

			@Override
			public void onResponse(ImageContainer response, boolean isImmediate) {
				if (response.getBitmap() != null) {
					// 在这里可以设置，如果想得到圆角图片的画，可以对bitmap进行加工，可以给imageview加一个
					// 额外的参数
					String urlTag = (String) view.getTag();
					if (urlTag != null && urlTag.trim().equals(url)) {
						view.setImageBitmap(response.getBitmap());
					}
				} else if (defaultImageResId != 0) {
					view.setImageResource(defaultImageResId);
				}
			}
		};
	}

	/**
	 * 判断连接的什么网络
	 * 
	 * @param context
	 * @return
	 */
	public static int getNetworkType(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		State gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		if (gprs == State.CONNECTED || gprs == State.CONNECTING) {
			return MOBILENET;
		}
		// 判断为wifi状态下才加载广告，如果是GPRS手机网络则不加载！
		if (wifi == State.CONNECTED || wifi == State.CONNECTING) {
			return WIFI;
		}

		return UNKNOW;
	}

	/**
	 * 检测网络是否连接
	 * 
	 * @return
	 */
	public static boolean checkNetworkState(Context context) {
		boolean flag = false;
		// 得到网络连接信息
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		// 去进行判断网络是否连接
		if (manager.getActiveNetworkInfo() != null) {
			flag = manager.getActiveNetworkInfo().isAvailable();
		}
		if (!flag) {
			// setNetwork();
		} else {
			// isNetworkAvailable();
		}

		return flag;
	}
}
